<template>
	<div class="situation">
		<div v-if="loading" class="loading">
			<a-spin :spinning="loading" tip="加载中..."></a-spin>
		</div>
		<div class="header">
			<div class="date">
				{{ date }}<span>{{ time }}</span>
			</div>
			<!-- <div class="alarm" @click="toAlarmCenterTable"><img src="@/global-assets/imgs/situation-home.png" />报警中心</div> -->
		</div>
		<div class="container">
			<div class="situation-left">
				<statistics :statistics-data="statisticsData" :loading="loadings.Statistics"></statistics>
				<div class="analysis">
					<monitoring-center-card title="报警分析" :header-bg="headerAlarmRecord" icon-name="alarm-analysis" width="18px" height="18px">
						<template #Header-Right>
							<div class="day">
								<p
									:key="index"
									v-for="(item, index) in day"
									:class="{ active: index === analysisIndex }"
									@click="alarmDayType(index, 'analysis')"
								>
									{{ item }} <span></span>
								</p>
							</div>
						</template>
						<template #Content>
							<alarm-analysis :loading="loadings.Analysis" :analysis-data="analysisData"></alarm-analysis>
						</template>
					</monitoring-center-card>
				</div>
			</div>
			<div class="situation-center video-content-box">
				<div class="video-content-grid">
					<template :key="item?.deviceId" v-for="item in currentConfig.deviceIds">
						<monitoring-center-video
							:info="item"
							:is-open-region="recognizeRegionSwitch"
							:screen-type="currentConfig.screenType"
						></monitoring-center-video>
					</template>
					<div :key="item" v-for="item in emptyNums" :class="`video-item${currentConfig.screenType}`">
						<div class="video-empty">
							<div class="empty-image">
								<global-svg-icon icon-name="camera-empty" width="48px" height="48px"></global-svg-icon>
								<div class="empty-description">选择设备</div>
							</div>
						</div>
					</div>
				</div>
				<div class="trend">
					<monitoring-center-card title="报警趋势" icon-name="alarm-trend" width="20px" height="19px" :header-bg="headerAlarm">
						<template #Header-Right>
							<div class="day">
								<p
									:key="index"
									v-for="(item, index) in day"
									:class="{ active: index === trendIndex }"
									@click="alarmDayType(index, 'trend')"
								>
									{{ item }} <span></span>
								</p>
							</div>
						</template>
						<template #Content>
							<alarm-trend :loading="loadings.Trend" :trend-data="trendData"></alarm-trend>
						</template>
					</monitoring-center-card>
				</div>
				<div class="region">
					<monitoring-center-card
						title="报警区域"
						icon-name="alarm-region"
						:header-bg="headerAlarm"
						width="16px"
						height="11px"
						vertical-align="inherit"
					>
						<template #Header-Left>TOP8</template>
						<template #Header-Right>
							<div class="day">
								<p
									:key="index"
									v-for="(item, index) in day"
									:class="{ active: index === regionIndex }"
									@click="alarmDayType(index, 'region')"
								>
									{{ item }} <span></span>
								</p>
							</div>
						</template>
						<template #Content>
							<alarm-region :loading="loadings.Region" :region-data="regionData"></alarm-region>
						</template>
					</monitoring-center-card>
				</div>
			</div>
			<div class="situation-right">
				<monitoring-center-card title="报警记录" icon-name="alarm-record" :header-bg="headerAlarmRecord" width="22px" height="22px">
					<template #Content>
						<div>
							<situation-alarm-record ref="alarmBarRef" @load-more="loadMore"></situation-alarm-record>
						</div>
					</template>
				</monitoring-center-card>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="situation">
import dayjs from 'dayjs';
import { videoPlay } from '@/global-utils/viedeo.utils';
import useSetInterval from '@/global-hooks/useSetInterval';
import headerAlarmRecord from '@/global-assets/imgs/alarm-title.png';
import headerAlarm from '@/global-assets/imgs/situation.png';
import { exceedAuthority } from '@/global-utils/base.utils';
import ScreenFullPlug from 'screenfull';
import { appStore } from '@/global-store/index';
import {
	Statistics,
	MonitoringCenterCard,
	AlarmAnalysis,
	SituationAlarmRecord,
	MonitoringCenterVideo,
	AlarmTrend,
	AlarmRegion
} from '../../components/index';
import type { Tsloadings, TsCurrentConfigProps, TsDeviceIdsItem, TsPlayerQueue, TsTreePropsTreeData } from '../../type';
import { realVideoApi } from '../../api';
import { findNodeByIndex } from '../../utils';

const { WebSocketStore } = appStore;
const { SocketState, ScoketSend } = WebSocketStore;

const token = window.sessionStorage.getItem('token');

const { LayoutStore } = appStore;

const loadings = reactive<Tsloadings>({
	Statistics: false,
	Analysis: false,
	Trend: false,
	Region: false,
	Record: false
});
const recognizeRegionSwitch = ref<boolean>(false); // 识别区域开关
const router = useRouter();
/**
 * 获取默认配置
 */
const currentConfig = ref<TsCurrentConfigProps>({
	aiTagStatus: false,
	deviceIds: [],
	id: 0,
	inspectionStatus: false,
	screenType: 1,
	userId: 0
});
const { clear } = useSetInterval();

// 跳转到监控中心
const { start: toLinkTimeStart, clear: toLinkTimeClear } = useSetInterval();
const loading = ref<boolean>(false);
// 报警中心
const toAlarmCenterTable = (): void => {
	loading.value = true;
	toLinkTimeStart(() => {
		loading.value = false;
		// 退出全屏后跳转
		ScreenFullPlug.exit();
		router.replace('/alarms-center');
	}, 1000);
};
const toAlarmCenter = (): void => {
	loading.value = true;
	toLinkTimeStart(() => {
		loading.value = false;
		router.replace('/monitoring-center/real-video');
	}, 1000);
};

const exitHandler = (): void => {
	const _document: any = document;
	if (!_document.webkitIsFullScreen && !_document.mozFullScreen && !_document.msFullscreenElement) {
		toAlarmCenter();
	}
};

const timer = ref<null | NodeJS.Timeout>();
const watchEffectStop = watchEffect(() => {
	timer.value && clearTimeout(timer.value);
	timer.value = setTimeout(() => {
		if (!LayoutStore.triggerScreen) {
			toAlarmCenter();
		}
	}, 500);
	// 判断页面刷新跳转监控中心
});

// 监听fullscreenchange事件（全屏模式的变化）
if (document.addEventListener) {
	document.addEventListener('webkitfullscreenchange', exitHandler, false);
	document.addEventListener('mozfullscreenchange', exitHandler, false);
	document.addEventListener('fullscreenchange', exitHandler, false);
	document.addEventListener('MSFullscreenChange', exitHandler, false);
}
// 报警分析
const analysisIndex = ref(1);
// 报警趋势
const trendIndex = ref(1);
// 报警区域
const regionIndex = ref(1);
// 获取记忆报警类型日期类型
// const getMemoryAlarmIndex = async (): Promise<void> => {
// 	try {
// 		let res: TsRes = await realVideoApi.getMemoryComper();
// 		if (res.code === 0) {
// 			analysisIndex.value = res.data.alarmAnalysis;
// 			trendIndex.value = res.data.alarmTrend;
// 			regionIndex.value = res.data.alarmArea;
// 		}
// 	} catch (error) {
// 		console.log('error', error);
// 	}
// };
// 查看更多
const loadMore = (): void => {
	// 全部报警
	router.push('/alarms-center');
};
// --------------------------------动态实时更新时间---------------------------------------
const time = ref('');
const date = ref('');
const updateTime = (): void => {
	date.value = dayjs(new Date()).format('YYYY - MM - DD ');
	time.value = dayjs(new Date()).format('HH : mm : ss');
};

// --------------------------------左边统计和报警分析---------------------------------------
// 统计
let statisticsData = ref({
	boxCountVos: {
		allNums: 1,
		onlineNums: 1,
		outlineNums: 1
	},
	deviceCountVos: {
		allNums: 1,
		onlineNums: 1,
		outlineNums: 1
	}
});

const getStatisticsData = async (): Promise<void> => {
	try {
		loadings.Statistics = true;
		let res: TsRes = await realVideoApi.getComprehensive();
		if (res.code === 0) {
			statisticsData.value = res.data;
			loadings.Statistics = false;
		}
	} catch (error) {
		console.log('error', error);
		loadings.Statistics = false;
	}
};

const day = ref(['昨日', '今日', '近7日']);
let dateDetail = ref({
	yesterday: {},
	today: {},
	last7Day: {}
});
let analysisData = ref({
	alarmAnalysisVoList: [],
	allAlarmCount: 0
});

// 时间类型
const dateType = (): void => {
	let cd = new Date();
	let todayDate = dayjs(cd).format('YYYY-MM-DD HH:mm:ss');
	let yesterdayDate = dayjs(cd).add(-1, 'day').format('YYYY-MM-DD');
	dateDetail.value.last7Day = {
		startTime: dayjs(cd).add(-7, 'day').format('YYYY-MM-DD 00:00:00'),
		endTime: todayDate
	};
	dateDetail.value.today = {
		startTime: dayjs(cd).format('YYYY-MM-DD 00:00:00'),
		endTime: todayDate
	};
	dateDetail.value.yesterday = {
		startTime: `${yesterdayDate} 00:00:00`,
		endTime: `${yesterdayDate} 23:59:59`
	};
};
const getAnalysisData = async (index?: number): Promise<void> => {
	try {
		loadings.Analysis = true;
		if (index || index === 0) {
			let params = Object.values(dateDetail.value)[index];
			let res: TsRes = await realVideoApi.analysis(params);
			if (res.code === 0) {
				analysisData.value = res.data;
				loadings.Analysis = false;
			}
		} else {
			let params = Object.values(dateDetail.value)[analysisIndex.value];
			let res: TsRes = await realVideoApi.analysis(params);
			if (res.code === 0) {
				analysisData.value = res.data;
				loadings.Analysis = false;
			}
		}
	} catch (error) {
		loadings.Analysis = false;
		console.log('error', error);
	}
};

// --------------------------------中间视频播放、报警趋势和报警区域---------------------------------------
// 空状态个数
const emptyNums = computed(() => currentConfig.value.screenType - currentConfig.value.deviceIds.length);
const treeData = ref([]); // 树数据
const flatObj: Record<string, any> = {};
const generateList = (data: TsTreePropsTreeData = []): void => {
	for (let i = 0; i < data.length; i++) {
		const node = data[i];
		flatObj[node.id] = node;
		if (node.children) {
			generateList(node.children);
		}
	}
};
// 摄像头推流
// const getVideoList = async (ids: any) => {
// 	// +++通过ids更新/摄像头推流
// 	await realVideoApi.getPlay(ids);
// };

const playerQueue = ref<TsPlayerQueue[]>([]);
// 播放视频
const videoRender = (videoParams: TsDeviceIdsItem, index: number): void => {
	videoParams.warningStatus = false;
	videoPlay({ videoDomId: `video${videoParams.id}`, videoUrl: videoParams.webrtc }, (play: any, videoStatus: number) => {
		videoParams.spinning = videoStatus;
		if (!playerQueue.value[index]) {
			playerQueue.value[index] = { play, key: videoParams.id };
		}
	});
};

let trendData = ref([]);

const getTrendData = async (index?: number): Promise<void> => {
	try {
		loadings.Trend = true;
		if (index || index === 0) {
			let params = Object.values(dateDetail.value)[index];
			let res: TsRes = await realVideoApi.trend(params);
			if (res.code === 0) {
				trendData.value = res.data;
				loadings.Trend = false;
			}
		} else {
			let params = Object.values(dateDetail.value)[trendIndex.value];
			let res: TsRes = await realVideoApi.trend(params);
			if (res.code === 0) {
				trendData.value = res.data;
				loadings.Trend = false;
			}
		}
	} catch (error) {
		loadings.Trend = false;
		console.log('error', error);
	}
};
let regionData = ref([]);
const getRegionData = async (index?: number): Promise<void> => {
	try {
		loadings.Region = true;
		if (index || index === 0) {
			let params = Object.values(dateDetail.value)[index];
			let res: TsRes = await realVideoApi.area(params);
			if (res.code === 0) {
				regionData.value = res.data;
				loadings.Region = false;
			}
		} else {
			let params = Object.values(dateDetail.value)[regionIndex.value];
			let res: TsRes = await realVideoApi.area(params);
			if (res.code === 0) {
				regionData.value = res.data;
				loadings.Region = false;
			}
		}
	} catch (error) {
		loadings.Region = false;
		console.log('error', error);
	}
};
// --------------------------------右侧报警记录---------------------------------------
const alarmBarRef = ref();
const getAlarmRecordData = async (): Promise<void> => {
	await alarmBarRef.value.getAlarmList(1, true, null);
};

// 判断报警类型
const alarmDayType = async (index: number, type: string): Promise<void> => {
	if (type === 'analysis') {
		getAnalysisData(index);
		analysisIndex.value = index;
	} else if (type === 'trend') {
		getTrendData(index);
		trendIndex.value = index;
	} else {
		getRegionData(index);
		regionIndex.value = index;
	}
	try {
		let params = {
			alarmAnalysis: analysisIndex.value,
			alarmArea: regionIndex.value,
			alarmTrend: trendIndex.value
		};
		let res: TsRes = await realVideoApi.postMemoryComper(params);
		if (res.code === 0) {
			analysisIndex.value = res.data.alarmAnalysis;
			trendIndex.value = res.data.alarmTrend;
			regionIndex.value = res.data.alarmArea;
		}
	} catch (error) {
		console.log('error', error);
	}
};

// 获取视频信息
const getVideoData = async (): Promise<void> => {
	try {
		let res: TsRes = await realVideoApi.getRemember();
		if (res && res.data) {
			recognizeRegionSwitch.value = res.data.identifyArea === 0 ? true : false;
			currentConfig.value.screenType = res.data.screenNums;
			currentConfig.value.deviceIds = findNodeByIndex(flatObj, res.data.playIds);
			currentConfig.value.deviceIds.forEach((item: TsDeviceIdsItem, index: number) => {
				videoRender(item, index);
			});
		}
	} catch (error) {
		console.log('error', error);
	}
};

const getTree = async (): Promise<void> => {
	try {
		let res: TsRes = await realVideoApi.tree();
		if (res) {
			generateList(res.data);
			treeData.value = res.data;
			await getVideoData();
		}
	} catch (error) {
		console.log('error', error);
	}
};
// ----------------------------------webSocket----------------------------------------------

SocketState.ws.onmessage = async (info: { data: string }) => {
	let obj = JSON.parse(info.data);
	if (obj) {
		exceedAuthority(obj);
		if (obj.message === 'ALARM_TREND') {
			// 报警趋势
			getTrendData();
		} else if (obj.message === 'ALARM_ANALYSIS') {
			// 报警分析
			getAnalysisData();
		} else if (obj.message === 'ALARM_AREA') {
			// 报警区域
			getRegionData();
		} else if (obj.message === 'BOX_NUMBER_MESSAGE') {
			// 盒子统计
			getStatisticsData();
		} else if (obj.message === 'ALARM_MESSAGE') {
			// 报警记录
			alarmBarRef.value.getData(obj.data);
		} else if (obj.data && obj.message === 'SEND_CHECK_VIDEO_MESSAGE') {
			await realVideoApi.getCheck({
				inspection: 1,
				ids: [...currentConfig.value.deviceIds.map((item) => item.areaOrDeviceId)]
			});
		}
	}
};

// 关闭所有视频
const videoAllClose = () => {
	playerQueue.value.forEach((item) => {
		item.play && item.play.close();
	});
};

const intervalTimer = ref();
onMounted(async () => {
	dateType();
	ScoketSend({ webPage: 'situation', userId: token, stater: 0 });
	intervalTimer.value && clearInterval(intervalTimer.value);
	intervalTimer.value = setInterval(() => {
		updateTime();
	}, 1000);
	// await getMemoryAlarmIndex();
	await getAlarmRecordData();
	await getStatisticsData();
	await getAnalysisData();
	await getTrendData();
	await getRegionData();
	await getTree();
});
onUnmounted(() => {
	ScoketSend({ webPage: 'situation', userId: token, stater: 1 });
	clear();
	toLinkTimeClear();
	videoAllClose();
	watchEffectStop();
	timer.value && clearTimeout(timer.value);
	intervalTimer.value && clearInterval(intervalTimer.value);
	document.removeEventListener('webkitfullscreenchange', exitHandler, false);
	document.removeEventListener('mozfullscreenchange', exitHandler, false);
	document.removeEventListener('fullscreenchange', exitHandler, false);
	document.removeEventListener('MSFullscreenChange', exitHandler, false);
});
</script>

<style lang="less" scoped>
@import url('../../style.less');

// 当前页面不需要的话, 可删除 style标签
.situation {
	width: 100vw;
	height: 100vh;
	background-image: url('@/global-assets/imgs/global-background.png');
	background-repeat: no-repeat;
	background-position: center;
	background-size: 100% 100%;

	.loading {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 99;
		width: 100%;
		height: 100%;
		padding-top: 300px;
		text-align: center;
		background: @mask05;
	}

	.header {
		display: flex;
		width: 100%;
		height: 76px;
		padding: 0 12px 0 23px;
		line-height: 76px;
		text-align: center;
		background: url('@/global-assets/imgs/situation-title1.png') no-repeat center bottom;
		background-size: 100% 100%;
		justify-content: space-between;

		.header-title {
			position: absolute;
			top: 18px;
			left: 50%;
			font-family: 'TENGXIANGZHIHEIJIAN';
			font-size: 32px;
			font-weight: 400;
			font-style: normal;
			line-height: normal;
			color: #fff;
			background: linear-gradient(180deg, #bdc4cb 0%, #fff 100%);
			background-clip: text;
			transform: translateX(-55px);
			-webkit-text-fill-color: transparent;
		}

		.date {
			font-family: 'D-DIN';
			font-size: 17px;
			line-height: 66px;
			color: rgba(255, 255, 255, 0.8);

			span {
				margin-left: 6px;
			}
		}

		.alarm {
			font-size: 16px;
			line-height: 66px;
			color: #fff;
			cursor: pointer;

			img {
				width: 15px;
				height: 16px;
				margin-top: -2px;
				margin-right: 8px;
				vertical-align: middle;
			}
		}
	}

	.container {
		display: flex;
		justify-content: space-between;
		padding: 35px 24px 24px;

		.day {
			display: flex;
			width: 141px;
			line-height: 24px;
			color: @text03;
			justify-content: space-between;
			cursor: pointer;

			.active {
				position: relative;
				color: @text02;

				span {
					position: absolute;
					bottom: 0;
					left: -3px;
					width: 36px;
					height: 2px;
					background: linear-gradient(
						90deg,
						rgba(22, 93, 255, 0) 0%,
						rgba(190, 218, 255, 0.92) 25%,
						rgba(232, 243, 255, 0.92) 50%,
						rgba(190, 218, 255, 0.92) 75%,
						rgba(22, 93, 255, 0) 100%
					);
				}
			}
		}

		.situation-left {
			width: 341px;
			height: 100%;

			.analysis {
				position: relative;
				height: 650px;
				border-radius: 8px;
				background: linear-gradient(0deg, rgba(8, 22, 59, 0.4), rgba(8, 22, 59, 0.4));
				box-shadow: 0 12px 12px 0 #00000059;
			}
		}

		.situation-center {
			display: flex;
			width: calc(100% - 730px);
			justify-content: space-between;
			flex-wrap: wrap;
			padding: 0;

			.video-content-grid {
				box-sizing: border-box;
				width: 100%;
				height: 674px;
				border: 1px solid rgba(32, 48, 91, 1);
				border-radius: 8px;
				padding: 8px 8px 2px;
				background: var(--mask-02, rgba(0, 0, 0, 0.12));
				box-shadow: 0 20px 40px 0 rgba(0, 0, 0, 0.25);
				gap: 0;

				.video-item1,
				.video-item2,
				.video-item3 {
					margin-right: 4px;
					margin-bottom: 4px;
					border: 1px solid;
					border-image-source: linear-gradient(158.09deg, rgba(255, 255, 255, 0.0225) 11.42%, rgba(255, 255, 255, 1.5e-5) 93.55%);
				}

				.video-item1 {
					height: 658px;
				}

				.video-item2 {
					overflow: hidden;
					width: calc(50% - 4px);
					height: 326px;
					border-radius: 2px;
				}

				.video-item3 {
					width: calc(33.33% - 5px);
					height: 214px;
				}

				.video-item1:last-child {
					margin-right: 0;
				}

				.video-item2:nth-child(2n) {
					margin-right: 0;
				}

				.video-item3:nth-child(3n) {
					margin-right: 0;
				}
			}

			.trend,
			.region {
				position: relative;
				width: calc(50% - 16px);
				margin-right: 32px;
				background: #0a1326;
				box-shadow: 0 12px 12px 0 rgba(0, 0, 0, 0.35);
			}

			.region {
				margin-right: 0;
			}
		}

		.situation-right {
			width: 341px;
			background: linear-gradient(0deg, rgba(8, 22, 59, 0.4), rgba(8, 22, 59, 0.4));
		}
	}
}
</style>
